<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:include="~{common/header :: commonHead}">
    <title>新增小票自助积分</title>
</head>
<style>
    #orgId{
        z-index: 999!important;
    }
    .id_option{
        z-index: 999!important;
    }
    .add_icon_button:after {
        content: "拍照上传";
        width: 100%;
        height: 20px;
        text-align: center;
        display: block;
        margin: 50% 0px 0px 0px;
        font-size: 14px;
        color: #686868;
    }
</style>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">

                    <h5 th:text="${'新增小票自助积分' }"></h5>

                    <div class="ibox-tools">
                    </div>
                </div>

                <div class="ibox-content">
                    <form class="row form-body form-horizontal m-t" method="post" th:action="${'/self_help_integral/add'}">
                        <div class="col-md-12 droppable sortable ui-droppable ui-sortable">
                            <div class="form-group draggable ui-draggable dropped" style="position: static;">
                                <label class="col-sm-3 control-label">用户手机号：</label>
                                <div class="col-sm-6">
                                    <input type="text" onblur="notice(this.value);" name="phone" th:value="${editable?.phone}" class="form-control usePhone" required="required" placeholder="请输入用户手机号">
                                    <span id="userInfo"  ></span>

                                </div>
                            </div>
                            <div class="form-group draggable ui-draggable dropped" style="position: static;">
                                <label class="col-sm-3 control-label">小票号：</label>
                                <div class="col-sm-6">
                                    <input type="text" name="ticketNum" th:value="${editable?.ticketNum}" class="form-control" required="required" placeholder="请输入小票号">
                                </div>
                            </div>
                            <div class="form-group draggable ui-draggable dropped" style="position: static;">
                                <label class="col-sm-3 control-label">上传图片：</label>
                                <div class="col-sm-2">
                                    <div class="add_icons">
                                        <div class="add_icon_pan" style="width: 210px">
                                            <input name="01_image" id="upload_pic_image" accept="image/*" control_id="image" image_id="imageId" class="upload_pic_input">
                                            <input class="form-control" id="imageId" name="imageId" type="text" th:value="${editable?.imageId}" style="display: none;">
                                            <input class="form-control" id="image" name="imgUrl" type="text" th:value="${editable?.imgUrl}" style="display: none;">
                                            <img id="uploaded_pic" th:class="${editable?.imgUrl != null ? '' : 'hide' }"
                                                 th:src="${editable?.imgUrl != null ? editable.imgUrl : ''}"/>
                                            <div th:class="'mark ' + ${editable?.imgUrl != null ? '' : 'hide' }">
                                                <div class="close_icon_button" control_id="image" image_id="imageId"></div>
                                            </div>
                                            <label for="upload_pic_image" th:class="'add_icon_button ' + ${editable?.imgUrl != null ? 'hide' : ''}"></label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group draggable ui-draggable dropped" style="position: static;">
                                <label class="col-sm-3 control-label">金额：</label>
                                <div class="col-sm-6">
                                    <input type="text" name="money" onkeyup="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'')" th:value="${editable?.money}" class="form-control" required="required"  placeholder="请输入金额">
                                </div>
                            </div>
                            <div class="form-group draggable ui-draggable dropped"  style="position: static;">
                                <label class="col-sm-3 control-label">消费时间：</label>
                                <div class="col-sm-6">
                                    <div class="input-group date">
                                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        <input readonly type="text" placeholder="选择消费时间" class="form-control" id="consume_time" name="consumeDay" th:value="${editable?.consumeDay}" required="required" autocomplete="off">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group draggable ui-draggable dropped" style="position: static;">
                                <label class="col-sm-3 control-label">选择商户：</label>
                                <div class="col-sm-6">
                                    <select required id="orgId" name="storeId" data-placeholder="请选择商户..." class="chosen-select form-control m-b" tabindex="1">
                                        <option value="">--请选择--</option>
                                        <option class="id_option" hassubinfo="true" th:each="storeInfoDTOs:${storeInfoDTO.storeDTOS}" th:selected="${storeInfoDTOs.id ==  editable?.storeId}" th:value="${storeInfoDTOs.id}" th:text="${storeInfoDTOs.storeFloor}+'  ' +${storeInfoDTOs.storeNum}+'  '+${storeInfoDTOs.storeName}"> </option>
                                    </select>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group draggable ui-draggable">
                                <div class="col-sm-12 col-sm-offset-3">
                                    <button class="btn btn-primary" id="submit-form" type="submit">保存内容</button>
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade in" id="addUser" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 400px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <button id="take" class="btn btn-primary btn-sm" title="拍照"><i class="glyphicon glyphicon-camera"></i></button>
            </div>
            <div class="modal-body" id="photo-box">
                <video id="v"></video>
                <canvas id="canvas" style="display:none;"></canvas>
                <!--<img style="width: 338px;height: 253px;" src="http://placehold.it/640&text=Your%20image%20here%20..." id="photo" alt="photo">-->
            </div>
        </div>
    </div>
</div>
<script th:inline="javascript">
    let consume_time;
    $("#submit-form").click(()=>{
        consume_time = $("#consume_time").val();

        if (consume_time==null||consume_time==''){
            layer.msg("请填写消费时间",{time: 500})
            return false;
        }

    });



    $('#consume_time').datepicker({
        autoclose: true,
        clearBtn: true, //清除按钮
        todayBtn: false, //今日按钮
        format: "yyyy-mm-dd",
        todayHighlight: true,
        endDate : new Date()
    });

    $(function () {
        var date = $("#consume_time").val();
        if (null == date || date == '') {
            let now = new Date();
            let time = now.getFullYear() + "-" +((now.getMonth()+1)<10?"0":"")+(now.getMonth()+1)+"-"+(now.getDate()<10?"0":"")+now.getDate();
            $("#consume_time").val(time)
        }
    });

    let ipDomain_ = [[${ipDomain}]];
    $("#upload_pic_image").click(e => {
        $("#addUser").modal('show');
    });
    $(function() {
        if ([[${isCommitted}]]) {
            layer.confirm('是否继续编辑？', {
                btn: ['是','否'] //按钮
            }, function(index){
                layer.close(index);
            }, function(){
                window.location.href = "/self_help_integral/list";

            });
        }
    });
    function notice(val) {

        $.get("getByMobile?mobile="+val, function (res) {
            if (res.resCode == 0) {
                layer.msg("姓名：" + res.data.name + "，积分：" + res.data.integral,{icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
                $("#userInfo").html("姓名：" + res.data.name + "，积分：" + res.data.integral);
                sessionStorage.setItem('userphone',val)
            }else if(res.resCode == 10025){
                layer.msg("该用户已冻结",{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
                $("#userInfo").html("该用户已冻结" );

            }
            else {
                layer.msg("用户不存在",{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
                $("#userInfo").html("用户不存在" );

            }
        });
    }
    $(function () {
        $("input[name=endtime]").datepicker({
        });
        $("#orgId").comboSelect();
        let error = [[${error}]];
        if (null != error) {
            layer.alert(error)
            // window.history.back(-1);
        }
    });


    $("#start_date").val(getNowFormatDate());
    $("#start_date").change(()=>{
        let _time = $("#start_date").val();
        let chosed = (new Date(_time));
        if (chosed > new Date()) {
            let _date = getNowFormatDate();
            $("#start_date").val(_date);
        }
    });
    function getNowFormatDate(){
        var day = new Date();
        var Year = 0;
        var Month = 0;
        var Day = 0;
        var CurrentDate = "";
        Year= day.getFullYear();//支持IE和火狐浏览器.
        Month= day.getMonth()+1;
        Day = day.getDate();
        CurrentDate += Year + '-';
        if (Month >= 10 ){
            CurrentDate += Month;
        }
        else{
            CurrentDate += "0" + Month;
        }
        if (Day >= 10 ){
            CurrentDate += '-' + Day ;
        }
        else{
            CurrentDate += "-0" + Day ;
        }
        return CurrentDate;
    }

    !(function () {
        // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function (constraints) {
                // 首先，如果有getUserMedia的话，就获得它
                var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

                // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
                if (!getUserMedia) {
                    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                }

                // 否则，为老的navigator.getUserMedia方法包裹一个Promise
                return new Promise(function (resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                });
            }
        }
        const constraints = {
            video: true,
            audio: false
        };
        let videoPlaying = false;
        let v = document.getElementById('v');
        let promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(stream => {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in v) {
                v.srcObject = stream;
            } else {
                // 防止再新的浏览器里使用它，应为它已经不再支持了
                v.src = window.URL.createObjectURL(stream);
            }
            v.onloadedmetadata = function (e) {
                v.play();
                videoPlaying = true;
            };
        }).catch((err) => {
            layer.msg("未检测到摄像头",{icon: 15,time: 1000,shade : [0.5 , '#000' , true]});
            $("#photo-box").html("<div style='text-align: center'><span style='color: #8D8D8D'>请连接摄像头</span></div>")
            console.error(err.name + ": " + err.message);
        })
        document.getElementById('take').addEventListener('click', function () {
            if (videoPlaying) {
                let canvas = document.getElementById('canvas');
                canvas.width = v.videoWidth;
                canvas.height = v.videoHeight;
                canvas.getContext('2d').drawImage(v, 0, 0);
                let data = canvas.toDataURL('image/webp');
                let formFile = new FormData();
                formFile.append("imgStr", data);
                $.ajax({
                    url: ipDomain_ + "/quanquan-resource/image/upload",
                    type:"post",
                    data: formFile,
                    dataType: 'JSON',
                    cache: false,
                    processData: false,
                    contentType: false
                }).done(function (res) {
                    if (res.resCode == 0) {
                        layer.msg("上传成功",{icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
                        $("#imageId").attr('value',res.data.id);
                        $("#image").attr('value',res.data.imageAddress);
                        console.log(res.data.imageAddress);
                    }
                });
                let image = $('#uploaded_pic');
                image.siblings('div.mark').removeClass('hide');
                image.attr("src", data).load(function() {
                    image.removeClass('hide')
                });
                image.siblings("label").addClass('hide');
            }
        }, false);
    })();

</script>
</body>
</html>